﻿using System;
using System.Globalization;
using System.Reflection;
using System.Windows;
using Meridian;
using VkApi;

namespace MeridianZ
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        private static readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();

        private const string AppId = "2635307";

        public static Settings Settings;
        public static readonly string Root = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
        public static Vkontakte Vkontakte;

        private void ApplicationStartup(object sender, StartupEventArgs e)
        {
            Vkontakte = new Vkontakte(AppId);
            Settings = (Settings)XmlSerializable.Load(typeof(Settings), Root + "\\MeridianZ.config") ?? new Settings();
            if (!string.IsNullOrEmpty(Settings.AccessToken) && Settings.ExpirationDate != DateTime.MinValue && !string.IsNullOrEmpty(Settings.UserId))
            {
                var authResult = new VkAuthResult(Settings.AccessToken, Settings.ExpirationDate, Settings.UserId);
                if (authResult.AccessToken.HasExpired)
                    return;
                Vkontakte.AuthResult = authResult;
                Global.IsAuthorized = true;
            }

            System.Threading.Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(Settings.Language);
        }

        private void ApplicationExit(object sender, ExitEventArgs e)
        {
            if (Global.IsAuthorized)
            {
                Settings.AccessToken = Vkontakte.AuthResult.AccessToken.Token;
                Settings.ExpirationDate = Vkontakte.AuthResult.AccessToken.Expires;
                Settings.UserId = Vkontakte.AuthResult.UserId;
            }
            Settings.Save(Root + "\\MeridianZ.config");
        }

        private void ApplicationDispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            logger.Fatal("An error occured.\n" + e.Exception);
            MessageBox.Show("An error occured. See details in log");
        }
    }
}
